//
//  WBNetWorkManger+Extension.swift
//  WeiBoApp
//
//  Created by James on 2017/6/19.
//  Copyright © 2017年 James. All rights reserved.
//

import Foundation

//封装新浪微博的网络请求方法
extension WBNetWorkManger{
    
    /// 加载微博数据 字典数组
    ///
    /// - Parameters:
    ///   - since_id: 返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。

    ///   - max_id: 返回ID小于或等于max_id的微博，默认为0。
    ///   - complete: 完成回调
    func statusList(since_id:Int64 = 0,max_id:Int64 = 0,complete:@escaping(_ list:[[String:AnyObject]]?,_ isSuccess:Bool)->()){
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let params = ["since_id":"\(since_id)" as AnyObject,"max_id":"\(max_id > 0 ? max_id-1:0)" as AnyObject]
        
        tokenRequest(URLString: urlString, parameters: params){
            (json,isSuccess) in
            //print(json)
            //冲json中获取 字典数组 
            //如果as?失败  list == nil
            let list =  json?["statuses"] as? [[String:AnyObject]]
            complete(list,isSuccess)
        }

    }
    
    //返回微博的未读数
    func  unreadCount(completion:@escaping(_ count:Int)->()){
        let  urlString = "https://rm.api.weibo.com/2/remind/unread_count.json" //请求的地址
        guard let uid = userAcount.uid else {
            return
        }
        let  params = ["uid":uid]
        
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]?){(json,ret) in
            let dict = json as? [String:AnyObject]
            let count = dict?["status"] as? Int
            
            completion(count ?? 0)
        }
        
    }

}

extension WBNetWorkManger {
    ///加载 accessToken
    
    
    /// 加载 accessToken
    ///
    /// - Parameters:
    ///   - code: 请求码
    ///   - completion: 完成的回调
    func loadAccessToken(code:String, completion:@escaping(_ isSuccess:Bool)->())  {
        
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        let parmar = ["client_id":WBAppkey as AnyObject,
                      "client_secret":WBAppSecert as AnyObject,
                      "grant_type":"authorization_code" as AnyObject,
                      "code":code as AnyObject,
                      "redirect_uri":WBRedirect_uri as AnyObject]  as [String:AnyObject]
        
        request(method: .POST, URLString: urlStr, parameters: parmar, complete: { (json,ret)in
            print(json)
            self.userAcount.yy_modelSet(with: (json as? [String:AnyObject]) ?? [:])
            
            print("获得的用户数据:\(self.userAcount)")
            
            //获取用户信息
            self.loadUserInfo(completion: { (dict) in
                print(dict)
                
                //设置用户的头像和昵称
                self.userAcount.yy_modelSet(with: dict)
                
                print(self.userAcount)
                
                completion(ret)//加载完用户信息后再回调
                
                //保存模型数据
                self.userAcount.saveAcount()
            })
        })
    }
}


extension WBNetWorkManger {
    func loadUserInfo(completion:@escaping(_ dict:[String:AnyObject])->())  {
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        guard let uid = userAcount.uid else {
            return
        }
        
        let params = ["uid":uid as AnyObject] as [String : AnyObject]
        
        tokenRequest(method: .GET, URLString: urlStr, parameters: params){ (json, ret) in
            print("获取到的用户信息\(json)")
            let retDict = json as? [String:AnyObject] ?? [:]
        
            completion(retDict)
        }
        
        
        
    }
}
